<?php

namespace app\common\model;

use think\Model;
use think\Request;
abstract class Base Extends Model
{
    // 用来判断用page还是limit方法
    protected $isPage;
    // 筛选条件
    protected $conditions;
    protected $page = 1;
    protected $pageSize = 10;
    protected $orderBy = false;
    protected $selectFields = true;
    protected $order;

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = false;
    protected $updateTime = false;
    // 追加属性
    protected $append = [
    ];

    const STATUS_NORMAL     = 'normal'; // 正常
    const STATUS_HIDDEN     = 'hidden'; // 已禁用
    const STATUS_LOCKED     = 'locked'; // 已锁定
    
    public function initialize()
    {
        $pageSize = Request::instance()->param('pageSize');
        if ($pageSize) {
            config('paginate.list_rows', $pageSize);
        }
        $this->isPage       = true;   
        $this->conditions   = [];
        $this->page         = 1;
        $this->pageSize     = 10;
        $this->orderBy      = false;
        $this->selectFields = true;
        $this->order = 'id DESC';
        parent::initialize();
    }

    protected function searchList()
    {
        $where = $this->prepareSearchConditions();

        $pageMethod = $this->isPage ? 'page' : 'limit';

        $model = $this->where($where)->$pageMethod($this->page, $this->pageSize)->field($this->selectFields);
        if ($this->order) {
            $list = $model->order($this->order)->select();
        } else {
            $list = $model->select();
        }
        
        return $list;
    }

    protected function searchCount()
    {
        $where = $this->prepareSearchConditions();

        return $this->where($where)->count();
    }

    final public function setSearchParam($param)
    {
        if (isset($param['isPage'])) {
            $this->isPage = $param['isPage'];
        }
        if (!empty($param['conditions'])) {
            $this->conditions = $param['conditions'];  
        }
        if (!empty($param['page'])) {
            $this->page = $param['page'];  
        }
        if (!empty($param['pageSize'])) {
            $this->pageSize = $param['pageSize'];  
        }
        if (!empty($param['orderBy'])) {
            $this->orderBy = $param['orderBy'];  
        }
        if (!empty($param['selectFields'])) {
            $this->selectFields = $param['selectFields'];  
        }
    }

    public function prepareSearchConditions () {
        if ($this->orderBy) {
            $this->order = $this->orderBy;
        }
        
        return $this->conditions;
    }
}
